package com.dailybule.java.dao;

import com.dailybule.java.bean.Emp;
import com.dailybule.java.db.DBManager;
import com.dailybule.java.bean.Emp;
import com.dailybule.java.db.DBManager;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class EmpDAO {

    private Connection conn;
    private PreparedStatement ps;
    private ResultSet rs;

    @SneakyThrows
    public List<Emp> find(){
        List<Emp> list = new ArrayList<>();
        // 1. 连接
        conn = DBManager.getConnection();
        // 2. 执行SQL
        String sql = "select * from emp where state=1";
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        // 3. 封装数据
        while(rs.next()){
            Emp emp = new Emp();
            emp.setEmpno(rs.getInt(1));
            emp.setEnname(rs.getString(2));
            emp.setJob(rs.getString(3));
            emp.setMgr(rs.getInt(4));
            emp.setHireDate(rs.getString(5));
            emp.setSal(rs.getDouble(6));
            emp.setComm(rs.getDouble(7));
            emp.setDeptNo(rs.getInt(8));
            emp.setState(1);
            list.add(emp);
        }
        return list;
    }

    @SneakyThrows
    public void save(Emp emp){
        String sql="insert into emp values (null,?,?,?,now(),?,?,?,1)";
        conn = DBManager.getConnection();
        ps = conn.prepareStatement(sql);
        ps.setString(1, emp.getEnname());
        ps.setString(2, emp.getJob());
        ps.setInt(3, emp.getMgr());
        ps.setDouble(4, emp.getSal());
        ps.setDouble(5, emp.getComm());
        ps.setInt(6, emp.getDeptNo());
        ps.executeUpdate();
    }
}